package logic

import (
	"context"
	"fmt"
	"math/rand"
	"product_zc/models/cache"
	"time"

	"product_zc/productRpc/internal/svc"
	"product_zc/productRpc/productRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SenSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSenSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SenSmsLogic {
	return &SenSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SenSmsLogic) SenSms(in *productRpc.SenSmsRequest) (*productRpc.SenSmsResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "sendSmsNum"+in.Tel).Result()
	result2, _ := cache.Rdb.Get(l.ctx, "sendSmsNum2"+in.Tel).Result()
	if result >= "1" {
		return nil, fmt.Errorf("当前验证码每分钟仅能发送一次")
	}
	if result2 >= "10" {
		return nil, fmt.Errorf("当前验证码一小时仅能发送十次")
	}

	code := rand.Intn(9000) + 1000

	//sms, err := pkg.SensSms(in.Tel, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(*sms.Body.Code)
	//}

	cache.Rdb.Set(l.ctx, "sendSms"+in.Tel, code, time.Minute*5)

	incr := cache.Rdb.Incr(l.ctx, "sendSmsNum"+in.Tel)
	incr2 := cache.Rdb.Incr(l.ctx, "sendSmsNum2"+in.Tel)
	if incr.Val() == 1 {
		cache.Rdb.Expire(l.ctx, "sendSmsNum"+in.Tel, time.Minute*1)
	}

	if incr2.Val() == 1 {
		cache.Rdb.Expire(l.ctx, "sendSmsNum2"+in.Tel, time.Hour*24)
	}
	return &productRpc.SenSmsResponse{}, nil
}
